
/*
 * @Date         : 2021-01-28 20:25:38
 * @LastEditors  : LiZhenglin
 * @LastEditTime : 2021-02-05 11:29:42
 * @FilePath     : \QianjiAutoRecord\Record.js
 */

// const myUtil = require("./utils/Util.js")
const save2Qianji = require("./utils/Save2Qianji.js")
const floatyInstance = require('./layout/FloatyInstance.js')

let Record = function () {
    this.analyze_param = null
    this.config_param = null
}

Record.prototype.init = function(books, accounts, global_config) {
    this.global_config = global_config

    let accounts_list = []
    let new_accounts = {}
    for(var i=0; i<accounts.length; ++i) {
        for(var key in accounts[i]) {
            new_accounts[key] = accounts[i][key]
            if(!myUtil.inList(accounts[i][key], accounts_list)) {
                accounts_list.push(accounts[i][key])
            }
        }
    }
    let books_list = []
    for(var key in books) {
        if(books[key]["enable"] && !myUtil.inList(key, books_list)) {
            books_list.push(key)
        }
    }

    this.config_param = {
        "accounts_dict": new_accounts,
        "books_dict": books,
        "accounts_list": accounts_list,
        "books_list": books_list
    }
}

Record.prototype.construct = function(type, money, account, remark, target) {
    this.analyze_param = {
        "type": type,
        "money": money,
        "account": this.config_param["accounts_dict"][account],
        "remark": remark,
        "target": target
    }
    floatyInstance.init(this.analyze_param, this.config_param, this.global_config)
    this.record_param = floatyInstance.getResult()
}

Record.prototype.record = function() {
    if(this.record_param) {
        save2Qianji.save(this.record_param)
    }

    let storage = storages.create("钱迹自动记账数据库")

    let type = this.record_param["type"]
    let catename = this.record_param["category"]
    let remark = this.record_param["remark"]
    let bookname = this.record_param["book"]
    let target = this.record_param["target"]
    let data_list = storage.get(target)

    if(!myUtil.isEmpty(remark) && remark.toString) {
        remark = remark.toString()
    }

    let data = {
        "type": type,
        "category": catename,
        "remark": remark,
        "book": bookname
    }
    
    if(!myUtil.isEmpty(target) && !myUtil.isEmpty(data_list)) { // 给该对象付过款
        let data_idx = myUtil.inDictList(data, data_list)
        if(data_idx == -1) {    // 未出现过
            data_list.push(data)
        } else {                // 出现过
            data_list = myUtil.toListEnd(data_idx, data_list)
        }
        storage.put(target, data_list)
    } else {    // 没有给这人付过款
        storage.put(target, [data])
    }
}

module.exports = new Record()